import { ref, reactive, onMounted, h, computed } from 'vue';
import { useMessage, useDialog } from 'naive-ui';
import {
  SearchOutline,
  PeopleOutline,
  DownloadOutline,
  EyeOutline,
  TrashOutline,
} from '@vicons/ionicons5';
import { createIndexColumn } from '@/utils/tableUtil';

export function useAuthorization() {
  const message = useMessage();
  const dialog = useDialog();

  // 搜索参数
  const searchParams = reactive({
    keyword: '',
    expertPool: null as string | null,
    role: null as string | null,
  });

  // 选项数据
  const roleOptions = [
    { label: '管理员', value: 'admin' },
    { label: '普通用户', value: 'user' },
  ];

  const expertPoolOptions = [
    { label: '计算机科学专家库', value: '1' },
    { label: '医学专家库', value: '2' },
    { label: '工程专家库', value: '3' },
  ];

  const userOptions = ref([
    { label: '张三 (EMP001)', value: '1' },
    { label: '李四 (EMP002)', value: '2' },
    { label: '王五 (EMP003)', value: '3' },
    { label: '赵六 (EMP004)', value: '4' },
    { label: '钱七 (EMP005)', value: '5' },
  ]);

  // 表格数据
  const loading = ref(false);
  const tableData = ref<any[]>([]);
  const checkedRowKeys = ref<string[]>([]);
  const pagination = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageCount: 0,
    onChange: (page: number) => {
      pagination.page = page;
      loadData();
    },
    onUpdatePageSize: (pageSize: number) => {
      pagination.pageSize = pageSize;
      pagination.page = 1;
      loadData();
    },
  });

  // 表格选择
  const rowSelection = {
    type: 'checkbox',
    multiple: true,
  };

  // 表格列定义
  const columns = computed(() => [
    createIndexColumn({
      currentPage: pagination.page,
      pageSize: pagination.pageSize,
    }),
    { title: '用户姓名', key: 'name', width: 120 },
    { title: '唯一标识', key: 'employeeId', width: 120 },
    { title: '专家库', key: 'expertPoolName', width: 180 },
    { 
      title: '权限角色', 
      key: 'role', 
      width: 120,
      render: (row: any) => {
        return row.role === 'admin' ? '管理员' : '普通用户';
      }
    },
    { title: '授权时间', key: 'authTime', width: 180 },
    { title: '备注', key: 'remark', width: 200 },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (row: any) => {
        return h('div', [
          h(
            'n-button',
            {
              size: 'small',
              type: 'info',
              ghost: true,
              onClick: () => handleViewDetail(row),
              style: 'margin-right: 8px',
            },
            { default: () => '详情' }
          ),
          h(
            'n-button',
            {
              size: 'small',
              type: 'error',
              ghost: true,
              onClick: () => handleRevoke(row),
            },
            { default: () => '撤销' }
          ),
        ]);
      },
    },
  ]);

  // 批量授权表单
  const showBatchModal = ref(false);
  const batchSubmitLoading = ref(false);
  const batchFormRef = ref();
  const batchFormData = reactive({
    expertPoolId: '',
    role: 'user',
    userIds: [],
    remark: '',
  });

  const batchRules = {
    expertPoolId: {
      required: true,
      message: '请选择专家库',
      trigger: 'change',
    },
    role: {
      required: true,
      message: '请选择权限角色',
      trigger: 'change',
    },
  };

  // 权限详情
  const showDetail = ref(false);
  const currentUser = ref<any>(null);
  const userPermissions = ref<any[]>([]);

  // 方法
  const rowKey = (row: any) => row.id;

  const loadData = () => {
    loading.value = true;
    // 模拟API调用
    setTimeout(() => {
      tableData.value = [
        {
          id: '1',
          name: '张三',
          employeeId: 'EMP001',
          department: '技术部',
          email: 'zhangsan@example.com',
          phone: '13800138001',
          expertPoolName: '计算机科学专家库',
          role: 'admin',
          status: 1,
          authTime: '2024-01-15 10:30:00',
          remark: '资深技术专家',
        },
        {
          id: '2',
          name: '李四',
          employeeId: 'EMP002',
          department: '研发部',
          email: 'lisi@example.com',
          phone: '13800138002',
          expertPoolName: '计算机科学专家库',
          role: 'user',
          status: 1,
          authTime: '2024-01-16 14:20:00',
          remark: '普通用户权限',
        },
        {
          id: '3',
          name: '王五',
          employeeId: 'EMP003',
          department: '医学部',
          email: 'wangwu@example.com',
          phone: '13800138003',
          expertPoolName: '医学专家库',
          role: 'admin',
          status: 1,
          authTime: '2024-01-10 09:15:00',
          remark: '医学专家库管理员',
        },
        {
          id: '4',
          name: '赵六',
          employeeId: 'EMP004',
          department: '工程部',
          email: 'zhaoliu@example.com',
          phone: '13800138004',
          expertPoolName: '工程专家库',
          role: 'user',
          status: 0,
          authTime: '2024-01-08 16:45:00',
          remark: '权限已撤销',
        },
      ];
      pagination.pageCount = 1;
      loading.value = false;
    }, 500);
  };

  const handleCheck = (keys: string[]) => {
    checkedRowKeys.value = keys;
  };

  const handleSearch = () => {
    pagination.page = 1;
    loadData();
  };

  const handleReset = () => {
    searchParams.keyword = '';
    searchParams.expertPool = null;
    searchParams.role = null;
    pagination.page = 1;
    loadData();
  };

  const handlePageChange = (page: number) => {
    pagination.page = page;
    loadData();
  };

  const handleBatchAuth = () => {
    Object.assign(batchFormData, {
      expertPoolId: '',
      role: 'user',
      userIds: [],
      remark: '',
    });
    showBatchModal.value = true;
  };

  const handleBatchSubmit = () => {
    batchFormRef.value?.validate((errors: any) => {
      if (!errors) {
        batchSubmitLoading.value = true;
        setTimeout(() => {
          message.success('批量授权成功');
          showBatchModal.value = false;
          batchSubmitLoading.value = false;
          loadData();
        }, 1000);
      }
    });
  };

  const handleExport = () => {
    message.info('导出功能开发中...');
  };

  const handleViewDetail = (row: any) => {
    currentUser.value = row;
    // 模拟获取用户权限详情
    userPermissions.value = [
      {
        id: '1',
        expertPoolName: '计算机科学专家库',
        role: 'admin',
        status: 1,
        authTime: '2024-01-15 10:30:00',
        remark: '管理员权限',
      },
      {
        id: '2',
        expertPoolName: '医学专家库',
        role: 'user',
        status: 1,
        authTime: '2024-01-20 14:15:00',
        remark: '普通用户权限',
      },
    ];
    showDetail.value = true;
  };

  const handleRevoke = (row: any) => {
    dialog.warning({
      title: '确认撤销权限',
      content: `确定要撤销用户"${row.name}"在"${row.expertPoolName}"的权限吗？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        message.success('权限撤销成功');
        loadData();
      },
    });
  };

  const handleRevokePermission = (permission: any) => {
    dialog.warning({
      title: '确认撤销权限',
      content: `确定要撤销用户在"${permission.expertPoolName}"的权限吗？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        message.success('权限撤销成功');
        // 重新加载权限详情
        handleViewDetail(currentUser.value);
      },
    });
  };

  // 组件挂载时加载数据
  onMounted(() => {
    loadData();
  });

  return {
    // 搜索相关
    searchParams,
    roleOptions,
    expertPoolOptions,
    userOptions,
    // 表格相关
    loading,
    tableData,
    checkedRowKeys,
    pagination,
    rowSelection,
    columns,
    rowKey,
    // 批量授权相关
    showBatchModal,
    batchSubmitLoading,
    batchFormRef,
    batchFormData,
    batchRules,
    // 权限详情相关
    showDetail,
    currentUser,
    userPermissions,
    // 方法
    handleCheck,
    handleSearch,
    handleReset,
    handlePageChange,
    handleBatchAuth,
    handleBatchSubmit,
    handleExport,
    handleViewDetail,
    handleRevoke,
    handleRevokePermission,
    // 图标组件
    SearchOutline,
    PeopleOutline,
    DownloadOutline,
    EyeOutline,
    TrashOutline,
  };
} 